// pages/receive/claim/claim.js
import api from '../../../utils/api';
import util from '../../../utils/util';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    canEdit: true,
    bank: '建设银行',
    username: '北京东方晨旭科技发展有限公司',
    columns: [],
    show: false,
    basicData: '', //基本信息
    invoiceList: [], // 发票
    taskList: [], // 任务号
    contractList: [], // 合同
    claimId: '', // 认领ID
    radioBill: '1', // 是否需要关联发票
    radioBillReason: '1', // 不需要关联发票理由
    radioContract: '1', // 是否需要关联合同
    businessTypes: [], // 业务类型选项
    // overduelist:'1' , // 出票单位是否在票交所公布的逾期名单内
    // whitelist:'1',  // 白名单
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.data.source = options.source ? options.source : ''
    //认领ID
    this.setData({
      claimId: options.claimId
    })
  },

  getData() {
    this.getTaskList()
    this.getinvoiceList()
    this.getContractList()
  },
  // 基本信息
  getBasicData() {
    let that = this;
    api.getClaimById({
      data: {
        claimId: that.data.claimId
      },
      success: function (res) {
        console.log(res)
        if (res.data.code == 200) {
          let now = new Date(res.data.data[0].claimDate);
          res.data.data[0].claimDate = util.formatTime(now).split(' ')[0];
          res.data.data[0].receiveMoney = util.formatFigure(res.data.data[0].receiveMoney)
          res.data.data[0].unclaimedMoney = util.formatFigure(res.data.data[0].unclaimedMoney)
          res.data.data[0].invoiceMoney = util.formatFigure(res.data.data[0].invoiceMoney)
          res.data.data[0].payableMoney = util.formatFigure(res.data.data[0].payableMoney)
          res.data.data[0].claimMoney = util.formatFigure(res.data.data[0].claimMoney)
          res.data.data[0].cusName = wx.getStorageSync('newcusname') ? wx.getStorageSync('newcusname') : res.data.data[0].cusName;
          res.data.data[0].cusId = wx.getStorageSync('newcusid') ? wx.getStorageSync('newcusid') : res.data.data[0].cusId;
          if (wx.getStorageSync('newcusname') || wx.getStorageSync('newcusid')) {
            wx.removeStorageSync('newcusname')
            wx.removeStorageSync('newcusid')
          }
          res.data.data[0].isScYqmd = res.data.data[0].isScYqmd === null ? res.data.data[0].isScYqmd : res.data.data[0].isScYqmd + ''
          res.data.data[0].isYcBmd = res.data.data[0].isYcBmd === null ? res.data.data[0].isYcBmd : res.data.data[0].isYcBmd + ''
          res.data.data[0].isOfflineClaimed = res.data.data[0].isOfflineClaimed === null ? res.data.data[0].isOfflineClaimed : res.data.data[0].isOfflineClaimed + ''
          that.setData({
            basicData: res.data.data[0],
            radioBill: res.data.data[0].needInvoice ? '1' : '0',
            radioBillReason: res.data.data[0].whyNoInvoice == '已在线下开票' || !res.data.data[0].whyNoInvoice ? '1' : res.data.data[0].whyNoInvoice == '先到款未开票'?'0':'2',
            radioContract: res.data.data[0].needContract ? '1' : '0'
          })
          that.getBusinessType()
        }
      }
    })

  },
  // 业务类型
  getBusinessType() {
    let that = this;
    api.getDkBusinessType({
      success: function (res) {
        if (res.data.code === 200) {
          that.data.columns = [];
          if (res.data.data.length > 0) {
            for (let i = 0; i < res.data.data.length; i++) {
              that.data.columns.push(res.data.data[i].dictValue)
            }
            that.setData({
              businessTypes: res.data.data,
              columns: that.data.columns
            })
          }
        }
        // that.data.basicData.businessType = that.data.basicData.businessType ? that.data.basicData.businessType : res.data.data[0].dictKey
        // if (res.data.code === 200) {
        //   that.setData({
        //     businessTypes: res.data.data,
        //     basicData: that.data.basicData
        //   })
        // }
      }
    })
  },
  // 下拉
  showPopup(e) {
    console.log(e.currentTarget.dataset.type)
    this.data.selectType = e.currentTarget.dataset.type;
    this.setData({
      show: true
    });
  },

  onCancel() {
    this.setData({
      show: false
    });
  },

  onConfirm(event) {
    console.log(event, "333")
    const {
      value
    } = event.detail;
    this.setData({
      bank: value,
      show: false
    })
    console.log(value)
    if (this.data.selectType == 0) {
      this.data.basicData.receiveType = value
    } else if (this.data.selectType == 1) {
      this.data.basicData.businessType = this.data.businessTypes.find(item => (
        item.dictValue === value
      )).dictKey
      console.log(this.data.basicData.businessType)
      this.data.basicData.businessTypeStr = value
    } else {
      this.data.basicData.responsibleDeptName = value
    }
    console.log(this.data.basicData.responsibleDeptName)
    console.log(this.data.basicData)
    this.setData({
      basicData: this.data.basicData
    })

  },
  // 到款类型
  ontypeInput(e) {
    console.log(e)
    this.data.selectType = e.currentTarget.dataset.type;
    this.getClaimType(e.detail)
  },
  ontypeChange(e) {
    console.log(e)
    this.data.basicData.receiveType = e.detail
  },
  onTypeFocus(e) {
    console.log(e)
    this.data.selectType = e.currentTarget.dataset.type;
    if (e.detail.value == '') {
      this.getClaimType(e.detail.value)
    }
  },
  onTypeClick(e) {
    this.data.selectType = e.currentTarget.dataset.type;
    this.getClaimType('')
  },
  // 获取到款类型
  getClaimType(value) {
    let that = this;
    api.getReceiveTypeDict({
      data: {
        searchStr: value
      },
      success: function (res) {
        if (res.data.code == 200) {
          that.data.columns = [];
          if (res.data.data.length > 0) {
            for (let i = 0; i < res.data.data.length; i++) {
              that.data.columns.push(res.data.data[i].dictValue)
            }
            that.setData({
              columns: that.data.columns
            })
            that.showPopup()
          } else {
            that.onCancel()
          }
        }
      }
    })
  },
  // 归口部门
  onDeptInput(e) {
    this.data.selectType = e.currentTarget.dataset.type;
    this.getDetpartment(e.detail)
  },
  onDeptChange(e) {
    this.data.basicData.responsibleDeptName = e.detail
  },
  onDeptFocus(e) {
    this.data.selectType = e.currentTarget.dataset.type;
    if (e.detail.value == '') {
      this.getDetpartment(e.detail.value)
    }
  },
  onDeptClick(e) {
    this.data.selectType = e.currentTarget.dataset.type;
    this.getDetpartment('')
  },
  getDetpartment(value) {
    let that = this;
    api.getResponsibleDeptDict({
      data: {
        searchStr: value
      },
      success: function (res) {
        if (res.data.code == 200) {
          that.data.columns = [];
          if (res.data.data.length > 0) {
            for (let i = 0; i < res.data.data.length; i++) {
              that.data.columns.push(res.data.data[i].dictValue)
            }
            that.setData({
              columns: that.data.columns
            })
            that.showPopup()
          } else {
            that.onCancel()
          }
        }
      }
    })
  },
  // 发票
  getinvoiceList() {
    let that = this;
    api.getClaimInvoiceByClaimId({
      data: {
        claimId: that.data.claimId
      },
      success: function (res) {
        console.log(res)
        if (res.data.code == 200) {
          for (let i = 0; i < res.data.data.length; i++) {
            res.data.data[i].claimMoney = util.formatFigure(res.data.data[i].claimMoney)
          }
          that.setData({
            invoiceList: res.data.data
          })
        }
      }
    })
  },

  // 任务号
  getTaskList() {
    let that = this;
    api.getClaimTaskByClaimId({
      data: {
        claimId: that.data.claimId
      },
      success: function (res) {
        console.log(res)
        if (res.data.code == 200) {
          for (let i = 0; i < res.data.data.length; i++) {
            res.data.data[i].claimMoney = util.formatFigure(res.data.data[i].claimMoney)
          }
          that.setData({
            taskList: res.data.data
          })
        }
      }
    })
  },
  // 合同
  getContractList() {
    let that = this;
    api.getClaimContractByClaimId({
      data: {
        claimId: that.data.claimId
      },
      success: function (res) {
        console.log(res)
        if (res.data.code == 200) {
          for (let i = 0; i < res.data.data.length; i++) {
            res.data.data[i].claimMoney = util.formatFigure(res.data.data[i].claimMoney)
          }
          that.setData({
            contractList: res.data.data
          })
        }
      }
    })
  },
  // 本次认领金额
  onChange(e) {
    console.log(this.data.basicData.claimMoney)
    this.data.basicData.claimMoney = parseFloat(e.detail.replace("¥", "").replace(/\s*/g, ''));
  },
  // 归口部门
  onChangeDept(e) {
    this.data.basicData.responsibleDeptName = e.detail
  },
  // 选择付款单位
  chooseFKDW() {
    // console.log(12312)
    wx.navigateTo({
      url: '/pages/receive/newWLDWlist/newWLDWlist',
    })
  },
  // 查看逾期名单
  onOverduelist() {
    wx.navigateTo({
      url: '/pages/receive/overduelist/overduelist',
    })
  },
  // 查看白名单
  onWhitelist() {
    wx.navigateTo({
      url: '/pages/receive/whitelist/whitelist',
    })
  },
  // 无合同原因
  onContractReasonChange(e) {
    this.data.basicData.whyNoContract = e.detail;
  },
  // 认领部分原因
  onPartReasonChange(e) {
    console.log(e)
    this.data.basicData.claimPartReason = e.detail
  },
  // 备注
  onRemarksChange(e) {
    console.log(e)
    this.data.basicData.remarks = e.detail
  },
  // 具体理由
  onReasonDetailChange(e) {
    console.log(e)
    this.data.basicData.whyNoInvoice2 = e.detail
  },

  // 业务类型 
  onBusiTypeChange(e) {
    console.log(e)
    this.data.basicData.businessType = e.detail;
    console.log(this.data.basicData.businessType)
    this.setData({
      basicData: this.data.basicData
    })
  },

  onMyEvent(e) {
    console.log(e)
    this.onTemporary()
    if (e.detail == 'del') {
      this.getBasicData()
      this.getData()
    }
  },
  // 是否需要关联发票
  onBillChange(e) {
    console.log(e)
    this.data.basicData.whyNoInvoice2 = ''
    this.setData({
      radioBill: e.detail,
      basicData: this.data.basicData
    })
  },
  onReasonChange(e) {
    console.log(e)
    this.data.basicData.whyNoInvoice2 = ''
    this.setData({
      radioBillReason: e.detail,
      basicData: this.data.basicData
    })
  },
  // 是否需要关联合同
  onContractChange(e) {
    console.log(e)
    this.data.basicData.whyNoContract = ''
    this.setData({
      radioContract: e.detail,
      basicData: this.data.basicData
    })
  },
  //出票单位是否在票交所公布的逾期名单内
  onOverdueChange(e) {
    console.log(e)
    this.data.basicData.isScYqmd = e.detail;
    this.setData({
      basicData: this.data.basicData
    })
  },
  //承兑方是否在财务公司发布的白名单内
  onWhiteChange(e) {
    console.log(e)
    this.data.basicData.isYcBmd = e.detail;
    this.setData({
      basicData: this.data.basicData
    })
  },
  onOfflineClaimed(e) {
    console.log(e)
    this.data.basicData.isOfflineClaimed = e.detail;
    this.setData({
      basicData: this.data.basicData
    })
  },
  // 提交
  onSubmit() {
    let that = this;

    if (that.data.basicData.claimMoney.indexOf('￥') != -1) {
      that.data.basicData.claimMoney = that.data.basicData.claimMoney.replace("¥", "")
    }
    if (that.data.basicData.claimMoney.indexOf(',') != -1) {
      that.data.basicData.claimMoney = that.data.basicData.claimMoney.replace(/,/g, '')
    }
    if (!that.data.basicData.cusId) {
      wx.showModal({
        content: "请选择付款单位",
        showCancel: false,
        confirmColor: '#0041C4'
      })
      return;
    }
    if (that.data.radioBill == '0' && that.data.radioBillReason == '0') {
      if (!that.data.basicData.whyNoInvoice2) {
        wx.showModal({
          content: "请填写具体原因",
          showCancel: false,
          confirmColor: '#0041C4'
        })
        return;
      }
    }
    if (that.data.radioContract === '0') {
      if (!that.data.basicData.whyNoContract) {
        wx.showModal({
          content: "请填写无合同原因",
          showCancel: false,
          confirmColor: '#0041C4'
        })
        return;
      }

    }
    if (that.data.basicData.isOfflineClaimed === null) {
      wx.showModal({
        content: "请选择线下是否已认领",
        showCancel: false,
        confirmColor: '#0041C4'
      })
      return;
    }

    if (that.data.basicData.isPartReason && !this.data.basicData.claimPartReason) {
      wx.showModal({
        content: "请输入认领部分原因",
        showCancel: false,
        confirmColor: '#0041C4'
      })
      return;
    }
    // that.data.basicData.claimMoney = parseFloat(that.data.basicData.claimMoney.replace("¥", "").replace(/\s*/g, ''));
    // console.log(that.data.basicData.receiveType)
    // console.log(that.data.basicData.responsibleDeptName)
    if (that.data.basicData.claimMoney !== NaN) {
      api.submitClaim({
        data: {
          id: that.data.claimId,
          claimMoney: that.data.basicData.claimMoney,
          responsibleDept: that.data.basicData.responsibleDeptName,
          receiveType: that.data.basicData.receiveType,
          remarks: that.data.basicData.remarks,
          claimPartReason:that.data.basicData.claimPartReason,
          needInvoice: that.data.radioBill,
          needContract: that.data.radioContract,
          whyNoInvoice2: that.data.basicData.whyNoInvoice2,
          whyNoInvoice: that.data.radioBill == '1' ? '' : that.data.radioBillReason == '1' ? '已在线下开票' : that.data.radioBillReason == '0'?'先到款未开票':'无需开票',
          businessType: that.data.basicData.businessType,
          whyNoContract: that.data.basicData.whyNoContract,
          cusId: that.data.basicData.cusId,
          isScYqmd: that.data.basicData.isScYqmd,
          isYcBmd: that.data.basicData.isYcBmd,
          isOfflineClaimed: that.data.basicData.isOfflineClaimed
        },
        method: 'POST',
        success: function (res) {
          console.log(res)
          if (res.data.code == 200) {
            wx.showToast({
              title: '提交成功',
            })
            setTimeout(() => {
              if (that.data.source) {
                wx.switchTab({
                  url: '/pages/receive/list/list',
                })
              } else {
                wx.navigateBack({
                  delta: 1,
                })
              }

            }, 100);
          } else {
            wx.showModal({
              content: res.data.message,
              showCancel: false,
              confirmColor: '#0041C4'
            })
          }
        }
      })
    } else {
      wx.showModal({
        content: "请正确填写认领金额",
        showCancel: false,
        confirmColor: '#0041C4'
      })
    }

  },
  // 保存

  onSave() {
    let that = this;
    if (that.data.basicData.claimMoney.indexOf('￥') != -1) {
      that.data.basicData.claimMoney = that.data.basicData.claimMoney.replace("¥", "")
    }
    if (that.data.basicData.claimMoney.indexOf(',') != -1) {
      that.data.basicData.claimMoney = that.data.basicData.claimMoney.replace(/,/g, '')
    }
    // that.data.basicData.claimMoney = parseFloat(that.data.basicData.claimMoney.replace("¥", "").replace(/,/g, ''));
    console.log(that.data.basicData.claimMoney)
    api.saveClaim({
      data: {
        id: that.data.claimId,
        claimMoney: that.data.basicData.claimMoney,
        responsibleDept: that.data.basicData.responsibleDeptName,
        receiveType: that.data.basicData.receiveType,
        whyNoInvoice2: that.data.basicData.whyNoInvoice2,
        remarks: that.data.basicData.remarks,
        claimPartReason:that.data.basicData.claimPartReason,
        needInvoice: that.data.radioBill,
        whyNoInvoice: that.data.radioBill == '1' ? '' : that.data.radioBillReason == '1' ? '已在线下开票' : that.data.radioBillReason == '0'?'先到款未开票':'无需开票',
        needContract: that.data.radioContract,
        businessType: that.data.basicData.businessType,
        whyNoContract: that.data.basicData.whyNoContract,
        cusId: that.data.basicData.cusId,
        isScYqmd: that.data.basicData.isScYqmd,
        isYcBmd: that.data.basicData.isYcBmd,
        isOfflineClaimed: that.data.basicData.isOfflineClaimed
      },
      method: 'POST',
      success: function (res) {
        console.log(res)
        if (res.data.code == 200) {
          wx.showToast({
            title: '保存成功',
          })
          // setTimeout(() => {
          //   if (that.data.source) {
          //     wx.switchTab({
          //       url: '/pages/receive/list/list',
          //     })
          //   } else {
          //     wx.navigateBack({
          //       delta: 1,
          //     })
          //   }
          // }, 100);
          that.getBasicData()
          that.getData()
        } else {
          wx.showModal({
            content: res.data.message,
            showCancel: false,
            confirmColor: '#0041C4'
          })
        }
      }
    })
  },
  // 临时
  onTemporary() {
    let that = this;
    if (that.data.basicData.claimMoney.indexOf('￥') != -1) {
      that.data.basicData.claimMoney = that.data.basicData.claimMoney.replace("¥", "")
    }
    if (that.data.basicData.claimMoney.indexOf(',') != -1) {
      that.data.basicData.claimMoney = that.data.basicData.claimMoney.replace(/,/g, '')
    }
    // that.data.basicData.claimMoney = that.data.basicData.claimMoney.replace("¥", "").replace(',','');
    console.log(that.data.basicData.claimDate)
    api.saveClaim({
      data: {
        id: that.data.claimId,
        claimMoney: that.data.basicData.claimMoney,
        responsibleDept: that.data.basicData.responsibleDeptName,
        receiveType: that.data.basicData.receiveType,
        whyNoInvoice2: that.data.basicData.whyNoInvoice2,
        remarks: that.data.basicData.remarks,
        claimPartReason:that.data.basicData.claimPartReason,
        needInvoice: that.data.radioBill,
        whyNoInvoice: that.data.radioBill == '1' ? '' : that.data.radioBillReason == '1' ? '已在线下开票' : that.data.radioBillReason == '0' ? '先到款未开票':'无需开票',
        needContract: that.data.radioContract,
        businessType: that.data.basicData.businessType,
        whyNoContract: that.data.basicData.whyNoContract,
        cusId: that.data.basicData.cusId,
        isScYqmd: that.data.basicData.isScYqmd,
        isYcBmd: that.data.basicData.isYcBmd,
        isOfflineClaimed: that.data.basicData.isOfflineClaimed
      },
      method: 'POST',
      success: function (res) {
        console.log(res)
        if (res.data.code == 200) {
          that.getBasicData()
          that.getData()
        } else {
          wx.showModal({
            content: res.data.message,
            showCancel: false,
            confirmColor: '#0041C4'
          })
        }
      }
    })
  },
  // 取消
  onCancelClaim() {
    let that = this;
    api.cancelClaim({
      data: {
        claimId: that.data.claimId
      },
      success: function (res) {
        if (res.data.code == 200) {
          wx.showToast({
            title: '取消成功',
          })
          setTimeout(() => {
            wx.navigateBack({
              delta: 1,
            })
          }, 100);
        } else {
          wx.showModal({
            content: res.data.message,
            showCancel: false,
            confirmColor: '#0041C4'
          })
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getBasicData()
    this.getData()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.onTemporary()
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})